﻿; (function ($) {
    //实例化table对象
    $.fn.hiTable = function (config) {

        var _table = null;
        var _config = {};
        var _checkbox = null;
        var undefined;
        //鼠标移动变化的颜色
        var _mouseovercolor = "#cfe1ff";//"#e9e9e9";

        initTable = function () {

            //this指针
            var _tb = this;
            //私有域
            //var signObj = {};

            //var signobj_inited = false;
            var sorttitle = (config.DefaultSortTitle == undefined ? "ID" : config.DefaultSortTitle),
                sortorder = (config.DefaultSortOrder == undefined ? "1" : config.DefaultSortOrder);
            //var oldsorttitle = undefined;
            //var signObj=sortorder;

            _config.tableId = config.tableId;
            _config.pageBarId = config.pageBarId;
            _config.ajaxURL = config.ajaxURL;
            _config.pageSize = 10;
            _config.currentPage = 0;
            _config.totalCount = 0;
            _config.sort = config.sort;
            _config.columnsConfig = config.columnsConfig;
            _config.fnDrawBody = config.fnDrawBody;
            _config.showCheckbox = config.showCheckbox;
            _config.nums = (config.nums == undefined ? 10 : config.nums);


            /*特权方法*/
            this.loadComplete = undefined;
            //对某个字段进行排序
            initTable.prototype.SortTable = function (title) {
                //alert(title);
                //if (signObj[title] == 0)
                //    signObj[title] = 1;
                //else
                //    signObj[title] = 0;
                if (title == sorttitle) {
                    //alert(url);
                    if (sortorder == 0)
                        sortorder = 1;
                    else
                        sortorder = 0;
                }
                else {
                    sortorder = 0;
                }
                //oldsorttitle = sorttitle
                _tb.sort(title, sortorder);

            }

            //修改表头
            initTable.prototype.ChangeHeader = function (id) {
                $("#" + id + " thead td").each(function (i, item) {
                    var title = $(config.columnsConfig)[i].Title;
                    var innertext = $.trim($(item).text().replace("&nbsp;", ""));
                    var innerhtml = $(item).html();
                    //var containinput=innertext.toLocaleLowerCase().indexOf("input")>0;
                    var containinput = innerhtml.indexOf("input") > 0;
                    if ((title != undefined) && (!containinput)) {
                        //if (!signobj_inited) {
                        //    if (title === sorttitle) {
                        //signObj.push({ title: sortorder });
                        //         signObj = sortorder;
                        //signObj.title=sortorder;
                        //     }
                        //     else {
                        //signObj.push({ title: 0 });
                        //        signObj = 0;
                        //signObj.title=0;
                        //   }
                        //}
                        //if (containinput)
                        //    $(item).html($("<div class=\"headcontainer\"><span><a href=\"#\">" + innertext + "</a></span></div>"));
                        //else
                        $(item).html($("<div class=\"headcontainer\"><span><a class=\"titlelink_"+_config.columnsConfig[i].Title+"\" href=\"#\">" + innertext + "</a></span><span class=\"triangle\">&nbsp;&nbsp;</span></div>"));

                        $(item).find("a").click(function () {
                            _tb.SortTable(title);
                        });
                    }

                });
                //signobj_inited = true;
            }

            


            //默认的排序回调
            this.sort = function (title, order) {
                _tb.sortfield(title, order);
            }

            initTable.prototype.sortfield = function (title, order) {
                /*var url = config.ajaxURL;
                if ($.trim(url.toLocaleLowerCase()).indexOf("?")>0) {
                url+="&";
                }
                else{
                url+="?";
                }
                url+="sort="+ title+"$"+order;
                alert(url);
                */
                sorttitle = title;
                sortorder = order;

                _tb.loadData(_config.pageSize, 0);
            };                      

            function drawing(pageSize, selectPageIndex) {
                return function (data) {
                    //清除全选按钮的状态
                    var selAll = $("#" + _config.tableId + ">thead :checkbox");
                    if (selAll.length > 0) {
                        _checkbox = selAll.get(0);
                        $(_checkbox).removeAttr("checked");
                    }
                   
                    var json = eval("(" + data + ")");
                    var html = '';
                    if (json == null) {
                        _config.totalCount = 1;
                        html = '';
                    }
                    else {
                        _config.totalCount = parseInt(json.Total);
                        if (typeof _config.fnDrawBody != "undefined")
                            html = _config.fnDrawBody(json.Data);
                        else
                            html = drawRow(json.Data);
                    }

                    //
                    $("#" + _config.tableId + " TBODY").empty().append(html); //装载数据   
                    //点击每行的复选框时，触发事件

                    //修改表头
                    _tb.ChangeHeader(_config.tableId);

                    onSelectRow();
                    onSelectAll();
                    //
                    if ($.find("#" + _config.pageBarId).length > 0)
                        drawPagebar();

                    //设置箭头
                    $("#" + _config.tableId + " thead td").each(function (i, item) {

                        var title = $(config.columnsConfig)[i].Title;
                        var innertext = $.trim($(item).text().replace("&nbsp;", ""));
                        var innerhtml = $(item).html();
                        var containinput = innerhtml.indexOf("input") > 0;
                        if ((title != undefined) && (!containinput)) {

                            $(item).find("a").css("background-image", "none");

                            //if (signobj_inited) {
                            //alert(signObj[title]);

                            if (sortorder == 0) {
                                //升序
                                //alert(signObj[title]);
                                $(item).find(".triangle").css("background-image", "url(/Content/images/hiTable/triangleup.png)");
                            }
                            else if(sortorder==1) {
                                //降序
                                //alert(signObj[title]);
                                $(item).find(".triangle").css("background-image", "url(/Content/images/hiTable/triangledown.png)");
                            }

                            }

                    });
                    //$(item).find(".triangle").hide();
                    $("#" + _config.tableId + " thead td .triangle").hide();
                    //alert(sorttitle);                            
                    //alert($("#" + _config.tableId + " thead td .headcontainer .titlelink"));
                    //alert( $("#" + _config.tableId + " thead td .headcontainer").html());
                   //alert( $("#" + _config.tableId + " thead td .headcontainer .titlelink_"+sorttitle).html());
                   $("#" + _config.tableId + " thead td .headcontainer .titlelink_"+sorttitle+"").parents(".headcontainer").find(".triangle").show();
                    //绘制完成后提供回调
                    if (_tb.loadComplete)
                        _tb.loadComplete(pageSize, selectPageIndex);

                }
            }
            function drawRow(data) {
                var html = '';
                if (typeof _config.columnsConfig != 'undefined') {

                    //循环行
                    $.each(data, function (i, item) {
                        var trcolor = i % 2 == 0 ? "even" : "odd";
                        html += "<tr class=\"" + trcolor + "\" onmouseover=\"initTable.ChangeColor(this);\">"

                       //循环列
                        for (var c = 0; c < _config.columnsConfig.length; c++) {
                            var col = _config.columnsConfig[c];
                            //Title:列名，Class：css样式,FnRender：自定义函数（生成td内的html）
                            var css = (typeof col.Class == 'undefined' ? '' : 'class=\"' + col.Class + '\"');
                             var content=null;
                            if(col.IsCheckbox)
                                 content = (typeof col.FnRender == 'undefined' ? "<input name=\"" + item[col.Title] + "\" type=\"checkbox\" />" : col.FnRender(item));
                            else
                                 content = (typeof col.FnRender == 'undefined' ? item[col.Title] : col.FnRender(item));

                             html += '<td ' + css + '>' + content + '</td>';
                        }
                        html += "</tr>";

                    });
                }
                return html;
            }
            function drawPagebar() {
                $("#" + _config.pageBarId).pagination(_config.totalCount, {
                    callback: selectPage(_config.pageSize),
                    items_per_page: _config.pageSize,
                    current_page: _config.currentPage,
                    num_display_entries: _config.nums
                });
            }
            //页码click事件
            function selectPage(pageSize) {
                return function (pageIndex, pageBar) {
                    _table.loadData(pageSize, pageIndex); 
                }
            }
            //当前页
            initTable.prototype.refresh = function(){
                _table.loadData(_config.pageSize, _config.currentPage); 
            }
            //从服务器读取数据
            initTable.prototype.loadData = function (pageSize, pageIndex) {
                _config.pageSize = pageSize;
                _config.currentPage = pageIndex;
                //使用ajax方式，调用action，读取数据
                $.ajax({type:"post",
                        url:_config.ajaxURL,
                        data:{PageIndex: pageIndex, PageSize: pageSize, Sort: sorttitle + "$" + sortorder },//URL中要传递的参数
                        beforeSend:Loading(XMLHttpRequest),//显示加载中图片
                        success:drawing(pageSize, pageIndex), //回调函数，当从服务器返回后，调用此函数
                        //error:function (XMLHttpRequest, textStatus, errorThrown) { alert("Error!");},//发生异常时触发此事件
                        //complete:function (XMLHttpRequest, textStatus) {alert("complete"); },//ajax事件结束时触发此事件
                        dataType:"json"////返回的数据类型
                });          
//                $.post(_config.ajaxURL, //要访问的URL地址
//                        {PageIndex: pageIndex, PageSize: pageSize, Sort: sorttitle + "$" + sortorder }, //URL中要传递的参数
//                         drawing(pageSize, pageIndex), //回调函数，当从服务器返回后，调用此函数
//                        "json"); //最后一个参数是返回的数据类型
                //阻止单击事件
                return false;
            }
            //显示加载中图片
            function Loading(XMLHttpRequest){
               $("#" + _config.tableId + " TBODY").empty().append("<tr><td colspan='"+_config.columnsConfig.length +"'><img style=\"width:110px;Height:80px\" src=\"/Content/images/loading.gif\" /></td></tr>");
            }
            function onSelectAll() {
                //var $selAll = $("#" + _config.tableId + ">thead :checkbox");
                //if ($selAll.length > 0) {
                if (_checkbox != null) {
                    //var checkbox = $selAll.get(0);
                                      
                    //全选
                    $(_checkbox).click(function () {
                        var flag = $(this).attr("checked");      
                        if (flag == true) {
                           
                            $("#" + _config.tableId + ">tbody>tr input[type=checkbox]").each(function () {
                                $(this).attr("checked", flag);
                            });
                        }
                        else {
                            $("#" + _config.tableId + ">tbody>tr input[type=checkbox]").each(function () {
                                $(this).removeAttr("checked");
                            });
                        }
                    });

                }
            }
            //如果全部选中勾上全选框，全部选中状态时取消了其中一个则取消全选框的选中状态
            function onSelectRow() {
                //var selAll = $("#" + _config.tableId + ">thead :checkbox");
                //if (selAll.length > 0) {
                if (_checkbox != null) {
                    $("#" + _config.tableId + ">tbody>tr input[type=checkbox]").each(function () {
                        $(this).click(function () {
                            if ($("#" + _config.tableId + ">tbody>tr input[type=checkbox]:checked").length == $("#" + _config.tableId + ">tbody>tr").length) {
                                $(_checkbox).attr("checked", "checked");
                            }
                            else $(_checkbox).removeAttr("checked");
                        });
                    });
                }
            }

            initTable.prototype.getSelected = function () {
                var ids = new Array();
                $("#" + _config.tableId + ">tbody>tr input[type=checkbox]:checked").each(function () {
                    ids.push($(this).attr("name"));
                });
                return ids;
            }
            //获取记录的总数
            initTable.prototype.getTotal = function(){return _config.totalCount;}
        }

        //类静态方法
        //鼠标移动变色相关
        initTable.ChangeColor = function (tr) {
            var obj = $(tr);
            var trcolor = obj.css("background-color");
            obj.css("background-color", _mouseovercolor);
            obj.mouseout(function () {
                obj.css("background-color", trcolor);
                delete (obj.mouseout);
            });
        }


        return _table = new initTable(config);
    }


})(jQuery);